package top.chenfu.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.chenfu.blog.beans.ResponseData;
import top.chenfu.blog.entity.User;
import top.chenfu.blog.service.UserService;

import java.util.Collection;

/**
 * @Auther chenfu
 * @2019/10/30 16:35
 * @Desc
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户名
     *
     * @return
     */
    @GetMapping("/currentUserName")
    public String currentUserName() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return principal.getUsername();
    }

    /**
     * 是否是超级管理员
     *
     * @return
     */
    @GetMapping("/isAdmin")
    public Boolean isAdmin() {
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        long count = authorities.stream().filter(authority -> authority.getAuthority().contains("超级管理员")).count();
        return count > 0;
    }

    @GetMapping("/currentUserEmail")
    public String currentUserEmail() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return principal.getEmail();
    }

    @PutMapping("/updateUserEmail")
    public ResponseData updateUserEmail(String email) {
        if (userService.updateUserEmail(email) > 0) {
            return ResponseData.defaultFail("开启成功！", null);
        }
        return ResponseData.defaultFail("开启失败！", null);
    }

    @RequestMapping("/login_page")
    public ResponseData loginPage() {
        ResponseData fail = ResponseData.defaultFail();
        fail.setMsg("尚未登录，请登录!");
        return fail;
    }

    @GetMapping("/hello")
    public ResponseData hello() {
        int x = 5/ 0;
        return ResponseData.defaultSuccess("hello World");
    }

}
